// pages/Protocol/ProtocolShareDetail/ProtocolShareDetail.js
//获取应用实例
const app = getApp()
const assetsAddress = app.globalData.global.assetsIp + '/' + app.globalData.global.assetsName;
import { queryUserIou } from '../../../api/protocol';
import { getBrandConfig } from '../../../api/brand';
import { getToken , codeLogin , Login } from '../../../api/login';
import { getUser , queryRealName } from '../../../api/user';
import { ACCESS_TOKEN } from '../../../utils/types';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    assetsAddress: assetsAddress,
    shareTitle: app.globalData.global.shareTitle,
    protocolId: '',
    protocol: {
      diffTime: 0,
    },
    closeDay: 0,
    user: {},
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if(options.scene){
      const scene = decodeURIComponent(options.scene)
      var arr = scene.split('---');
      this.setData({
        parentUserId: arr.length > 1 ? arr[0] : scene,
        protocolId: arr.length > 1 ? arr[1] : '',
      })
      this.login();
    }else{
      if(options.protocolId){
        this.setData({
          protocolId: options.protocolId,
        })
        this._getBrandConfig();
        this._getUser();
      }
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    let userId = wx.getStorageSync('userId')
    return {
      title: this.data.shareTitle,
      imageUrl: '../ProtocolUserSuccess/images/shareImage.png',
      path: '/pages/Protocol/ProtocolShareDetail/ProtocolShareDetail?scene='+userId + '---' + this.data.protocolId,
    }
  },
  _getBrandConfig(){
    let _this = this;
    getBrandConfig({})
    .then(res => {
      if(res.success){
        _this.setData({
          closeDay: res.data[0].iouAutoCloseDay ?? 30,
        })
        _this.getDetail();
      }else{
        wx.showToast
      }
    })
  },
  getDetail(){
    let _this = this;
    queryUserIou({protocolId: _this.data.protocolId})
    .then(res => {
      if(res.success){
        var element = res.data.content[0];
        var itemTime = element.createTime.replace(/-/g,'/')
        var createTime = new Date(itemTime).getTime();
        var nowTime = new Date().getTime();
        var diffTime = createTime - nowTime + parseInt(_this.data.closeDay) * 24 * 3600 * 1000;
        if(diffTime < 0 && element.status == '0'){
          element.status = '2'
        }
        element.diffTime = diffTime;
        _this.setData({
          protocol: element,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 登录
  login(){
    // 获取服务器token
    getToken().then(res => {
      let _this = this;
      if(res.success){
        wx.setStorageSync(ACCESS_TOKEN, res[ACCESS_TOKEN]);
        // 登录
        wx.login({
          success: logRes => {
            // 发送 res.code 到后台换取 openId, sessionKey, unionId
            console.log(logRes,'logRes')
            if (logRes.code) {
              codeLogin(logRes.code,_this.data.parentUserId)
              .then(rres => {
                console.log(rres,'第一次登录返回的rres')
                if(rres.success){
                  wx.setStorageSync(ACCESS_TOKEN, rres.access_token);
                  wx.setStorageSync('expires_in', rres.expires_in);
                  getUser({})
                  .then(user => {
                    if(user.success){
                      wx.setStorageSync('userId', user.data.userId)
                      wx.setStorageSync('phone', user.data.phone)
                      _this.setData({user: user.data})
                      _this._getBrandConfig();
                    }
                  })
                }else{
                  wx.showToast({
                    title: rres.errMessage,
                    icon: 'none',
                  })
                }
              })
            } else {
              wx.showToast({
                title: logRes.errMsg,
                icon: 'none',
              })
            }
          },
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none'
        })
      }
    })
  },
  // 获取用户信息和实名信息
  _getUser(){
    let _this = this;
    getUser()
    .then(res => {
      if(res.success){
        _this.setData({
          user: res.data,
        })
        if(res.data.realName){
          _this._queryRealName();
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  _queryRealName(){
    let _this = this;
    queryRealName()
    .then(res => {
      if(res.success){
        _this.setData({
          idNumber: res.data.idNumber,
        })
        console.log(res.data.idNumber,'idNumber')
        console.log(_this.data.idNumber,'idNumber')
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 查看借条
  goDetail(){
    let _this = this;
    if(_this.data.protocol.createUserId == _this.data.user.userId){
      wx.navigateTo({
        url: `/pages/Protocol/ProtocolDetail/ProtocolDetail?protocolId=${_this.data.protocolId}`,
      })
    }else{
      if(_this.data.user.realName == null || _this.data.user.realName == ''){
        wx.showModal({
          title: '温馨提示',
          content: _this.data.user.phone.length != 11 ? '暂未绑定手机号，是否前往绑定？' : '请先补充信息后再进行操作',
          complete: (res) => {
            if (res.confirm) {
              if(_this.data.user.phone.length != 11){
                wx.navigateTo({
                  url: '/pages/Users/BindPhone/BindPhone',
                  events: {
                    'updateUser': function(data){
                      _this._getUser();
                    }
                  }
                })
              }else{
                wx.navigateTo({
                  url: '/pages/Users/RealName/RealName',
                  events: {
                    'updateUser': function(data){
                      _this._getUser();
                    }
                  }
                })
              }
            }
          }
        })
        return;
      }
      var otherUserName = '';
      if(_this.data.protocol.lendUserSignatureImgUrl == null || _this.data.protocol.lendUserSignatureImgUrl == ''){
        otherUserName = _this.data.protocol.lendName;
      }else if(_this.data.protocol.borrowUserSignatureImgUrl == null || _this.data.protocol.borrowUserSignatureImgUrl == ''){
        otherUserName = _this.data.protocol.borrowName;
      }
      if(otherUserName != '' && otherUserName != null && otherUserName != _this.data.user.realName){
        wx.showToast({
          title: '当前借条与您的信息不匹配，无法查看',
          icon: 'none',
        })
        return;
      }
      wx.navigateTo({
        url: `/pages/Protocol/ProtocolDetail/ProtocolDetail?protocolId=${_this.data.protocolId}`,
      })
    }
  },
})